package com.example.demo.zaqizabatest.多线程相关;

import lombok.SneakyThrows;

/**
 * @ClassName 打印数字
 * @Author lys4134
 * @Date 2021/08/27 16:49:05
 * @Description 打印数字
 * <p>
 * 启动3个线程打印递增的数字,
 * 线程1先打印1,2,3,4,5,
 * 然后是线程2打印6,7,8,9,10,
 * 然后是线程3打印11,12,13,14,15.
 * 接着再由线程1打印16,17,18,19,20….以此类推, 直到打印到75
 * @Version 1.0
 **/
@SuppressWarnings("AlibabaAvoidManuallyCreateThread")
public class 打印数字 implements Runnable {
    private static volatile int printNum = 0;

    private Object object;
    private int threadId;


    public 打印数字(Object object, int threadId) {
        this.object = object;
        this.threadId = threadId;
    }

    private void printNum() {
        String name = Thread.currentThread().getName();
        for (int i = 1; i < 76; i++) {
            System.out.println(name + ": " + i);
        }
    }

    public static void main(String[] args) {
        Object o = new Object();
        new Thread(new 打印数字(o, 1)).start();
        new Thread(new 打印数字(o, 2)).start();
        new Thread(new 打印数字(o, 3)).start();

    }

    /**
     *   0  1
     *   5  2
     *  10  3
     *  15  1
     *  20  2
     *  25  3
     */

    @SneakyThrows
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        while (printNum < 75) {
            synchronized (object) {
                if (printNum / 5 % 3 + 1 == threadId) {
                    for (int i = 0; i < 5; i++) {
                        System.out.println("线程" + threadId + ":" + (++printNum));
                    }
                    object.notifyAll();
                } else {
                    try {
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
